package net.xiangcaowuyu.log4j.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Slf4j
public class LogAspect {

    /**
     * 开始时间
     * 通过ThreadLocal处理并发
     */
    ThreadLocal<Long> beginTime = new ThreadLocal<>();

    /**
     * 定义切点
     * 所有controller包下的public方法
     */
    @Pointcut("execution(public * net.xiangcaowuyu.log4j.controller..*.*(..))")
    public void autoLog() {
    }

    /**
     * 方法执行前
     *
     * @param joinPoint 切点
     */
    @Before("autoLog()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert servletRequestAttributes != null;
        HttpServletRequest request = servletRequestAttributes.getRequest();
        log.info("method---" + request.getMethod());
        beginTime.set(System.currentTimeMillis());
    }

    @After("autoLog()")
    public void doAfter(JoinPoint joinPoint) {
        long endTime = System.currentTimeMillis();
        log.info("耗时：" + (endTime - beginTime.get()));
    }
}
